package com.demo.uploadpic_base64;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.util.Log;

/**
 * 上传图片工具
 * 
 * @author Mr.Y
 * 
 */
public class UpLoadImage {

	/** 命名空间、即上传图片的服务器接口 */
	private static String NAME_SPACE = "http://tempuri.org";

	private static String SOAP_ACTION = "http://tempuri.org/FileUploadImage";

	/** 对应的URL */
	private static String requestURL = "http://www.jishanghui.cn/WebService.asmx";

	private static String RESULT = "WebService_BackContent";

	/**
	 * 
	 * 使用ksoap2调用webServic
	 * 
	 * @param methodName
	 * @param fileName
	 * @param imageBuffer
	 * @return
	 * @throws Exception
	 */
	public static final boolean connectWebService(String methodName,
			String fileName, String bytestr) throws Exception {

		Object result = null;
		// bytestr = "";
		//
		// String xml = UpLoadImage.class.getClassLoader()
		// .getResource("soap_xml.xml").getFile();
		// String xmlFile = replace(xml, "string", bytestr).getPath();
		// URL url = new URL(requestURL);
		// HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// File fileToSend = new File(xml);
		// byte[] buf = new byte[(int) fileToSend.length()];
		// new FileInputStream(xml).read(buf);
		// conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
		// conn.setRequestProperty("Content-Length",
		// String.valueOf(buf.length));
		// conn.setRequestProperty("SOAPAction", SOAP_ACTION);
		// conn.setRequestMethod("POST");
		// conn.setDoInput(true);
		// conn.setDoOutput(true);
		// OutputStream out = conn.getOutputStream();
		// out.write(buf);
		// out.close();
		// byte[] datas = readInputStream(conn.getInputStream());
		// String result1 = new String(datas);
		//
		// try {
		// Log.i(RESULT, result1.toString());
		//
		// return true;
		//
		// } catch (Exception e) {
		// e.printStackTrace();
		// return false;
		// }

		// 以下就是调用过程了
		SoapObject soapObject = new SoapObject(NAME_SPACE, methodName);
		soapObject.addProperty("fileName", fileName);// 图片名
		soapObject.addProperty("image", bytestr);// 图片字符串把图片转成64字符串流
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER10);
		envelope.dotNet = true;
		envelope.bodyOut = soapObject;
		envelope.setOutputSoapObject(soapObject);
		envelope.encodingStyle = SoapSerializationEnvelope.ENC;
		HttpTransportSE transportSE = new HttpTransportSE(requestURL);

		try {
			transportSE.call(SOAP_ACTION, envelope);
			result = envelope.getResponse();
			Log.i(RESULT, result.toString());

			return true;

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	/**
	 * 文件内容替换
	 * 
	 * @param inFileName
	 *            源文件
	 * @param from
	 * @param to
	 * @return 返回替换后文件
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	public static File replace(String inFileName, String from, String to)
			throws IOException, UnsupportedEncodingException {
		File inFile = new File(inFileName);
		BufferedReader in = new BufferedReader(new InputStreamReader(
				new FileInputStream(inFile), "utf-8"));
		File outFile = new File(inFile + ".jpg");
		PrintWriter out = new PrintWriter(new BufferedWriter(
				new OutputStreamWriter(new FileOutputStream(outFile), "utf-8")));
		String reading;
		while ((reading = in.readLine()) != null) {
			out.println(reading.replaceAll(from, to));
		}
		out.close();
		in.close();
		// infile.delete(); //删除源文件
		// outfile.renameTo(infile); //对临时文件重命名
		return outFile;
	}

	/**
	 * 从输入流中读取数据
	 * 
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	public static byte[] readInputStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();// 网页的二进制数据
		outStream.close();
		inStream.close();
		return data;
	}

	private static final String TAG = "uploadFile";
	private static final int TIME_OUT = 10 * 10000000; // 超时时间
	private static final String CHARSET = "utf-8"; // 设置编码
	public static final String SUCCESS = "1";
	public static final String FAILURE = "0";

	public static String uploadFile(File file) {
		String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
		String PREFIX = "--", LINE_END = "\r\n";
		String CONTENT_TYPE = "multipart/form-data"; // 内容类型
		String RequestURL = "http://192.168.1.112/web/MyServlet";
		try {
			URL url = new URL(RequestURL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(TIME_OUT);
			conn.setConnectTimeout(TIME_OUT);
			conn.setDoInput(true); // 允许输入流
			conn.setDoOutput(true); // 允许输出流
			conn.setUseCaches(false); // 不允许使用缓存
			conn.setRequestMethod("POST"); // 请求方式
			conn.setRequestProperty("Charset", CHARSET); // 设置编码
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
					+ BOUNDARY);
			if (file != null) {
				/**
				 * 当文件不为空，把文件包装并且上传
				 */
				// OutputStream outputSteam = conn.getOutputStream();

				DataOutputStream dos = new DataOutputStream(
						conn.getOutputStream());
				StringBuffer sb = new StringBuffer();
				sb.append(PREFIX);
				sb.append(BOUNDARY);
				sb.append(LINE_END);

				/**
				 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
				 * filename是文件的名字，包含后缀名的 比如:abc.png
				 */
				sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""
						+ file.getName() + "\"" + LINE_END);
				sb.append("Content-Type: application/octet-stream; charset="
						+ CHARSET + LINE_END);
				sb.append(LINE_END);
				dos.write(sb.toString().getBytes());
				InputStream is = new FileInputStream(file);
				byte[] bytes = new byte[100 * 1024];
				int len = 0;
				while ((len = is.read(bytes)) != -1) {
					dos.write(bytes, 0, len);
				}
				is.close();
				dos.write(LINE_END.getBytes());
				byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
						.getBytes();
				dos.write(end_data);
				dos.flush();
				/**
				 * 获取响应码 200=成功 当响应成功，获取响应的流
				 */
				int res = conn.getResponseCode();
				if (res == 200) {
					return SUCCESS;
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return FAILURE;
	}

	/* 上传文件至Server的方法 */
	public static String uploadFile_01(File file) {
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		String actionUrl = "http://192.168.1.112/web/MyServlet";
		try {
			URL url = new URL(actionUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			/* 允许Input、Output，不使用Cache */
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			/* 设置传送的method=POST */
			con.setRequestMethod("POST");
			/* setRequestProperty */
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			/* 设置DataOutputStream */
			DataOutputStream ds = new DataOutputStream(con.getOutputStream());
			ds.writeBytes(twoHyphens + boundary + end);
			// ds.writeBytes("Content-Disposition: form-data; "
			// + "name=\"file1\";filename=\"" + new Name + "\"" + end);
			ds.writeBytes(end);
			/* 取得文件的FileInputStream */
			FileInputStream fStream = new FileInputStream(file);
			/* 设置每次写入1024bytes */
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];
			int length = -1;
			/* 从文件读取数据至缓冲区 */
			while ((length = fStream.read(buffer)) != -1) {
				/* 将资料写入DataOutputStream中 */
				ds.write(buffer, 0, length);
			}
			ds.writeBytes(end);
			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
			/* close streams */
			fStream.close();
			ds.flush();
			/* 取得Response内容 */
			InputStream is = con.getInputStream();
			int ch;
			StringBuffer b = new StringBuffer();
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
			}
			/* 关闭DataOutputStream */
			ds.close();
			return "1";
		} catch (Exception e) {
			return "0";
		}
	}

}
